package com.localcache.server.init;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * netty 服务管理 启动器
 *
 * @author chennengcheng
 * @date 2021-09-14 9:41
 * @remark
 */
public class CacheManagerServer {

    private static final Logger log = LoggerFactory.getLogger(CacheManagerServer.class);

    public static ChannelHandlerContext cacheClientHandler;

    private Integer port;

    private ServerBootstrap bootstrap;

    private final EventLoopGroup bossGroup = new NioEventLoopGroup();

    private final EventLoopGroup workerGroup = new NioEventLoopGroup();

    public CacheManagerServer(Integer port) {
        this.port = port;
    }

    /**
     * 初始化 nettyServer
     */
    public void initNettyServer(){
        try {
            // 客户端启动类程序
            bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.option(ChannelOption.SO_SNDBUF , 1024 * 1024 * 2);
            bootstrap.option(ChannelOption.SO_RCVBUF , 1024 * 1024 * 2);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new LocalCacheServerInitializer());
            ChannelFuture cf = bootstrap.bind(port).sync();
            log.info("######################### server start #########################");
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
                e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
